package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.enums.CacheKey;
import com.qingcheng.pojo.goods.Category;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.PreferentialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ProjectName: qingcheng_parent
 * @ClassName: CartServiceImpl
 * @Time: 2019/7/17
 * @Author: zhou24
 * @Description:
 * @Experience:
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private CategoryService categoryService;

    @Reference
    private SkuService skuService;

    @Override
    public List<Map<String, Object>> findCartList(String username) {
        if (username==null){
            throw new RuntimeException("username为空");
        }
        System.out.println("从redis中提取购物车"+username);
        List<Map<String, Object>> cartList = (List<Map<String, Object>>) redisTemplate.boundHashOps(CacheKey.CART_LIST).get(username);
        if (cartList==null){
            return new ArrayList<>();
        }
        return cartList;
    }

    @Override
    public void addItem(String username, String skuId, Integer num) {
        List<Map<String, Object>> cartList = findCartList(username);
        Boolean flag = false;
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if (skuId.equals(orderItem.getSkuId())){
                //更新cartList商品信息
                if (orderItem.getNum()<=0){
                    cartList.remove(map);
                    break;
                }
                //单个商品重量
                int weight=orderItem.getWeight()/orderItem.getNum();
                orderItem.setNum(orderItem.getNum()+num);
                //如果数量小于等于0
                if(orderItem.getNum()<=0){
                    //购物车项删除
                    cartList.remove(map);
                    break;
                }
                //金额计算
                orderItem.setMoney( orderItem.getNum()*orderItem.getPrice() );
                //重量计算
                orderItem.setWeight( weight*orderItem.getNum() );
                flag=true;
                break;
            }
        }
        //如果购物车中原本没有该商品，则添加
        if (!flag){
            //商品合法性判断
            Sku sku = skuService.findById(skuId);

            if(sku==null){
                throw new RuntimeException("商品不存在");
            }
            if(!"1".equals(sku.getStatus())){
                throw new RuntimeException("商品状态不合法");
            }
            //数量不能为0或负数
            if(num<=0){
                throw new RuntimeException("商品数量不合法");
            }

            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(skuId);
            orderItem.setSpuId(sku.getSpuId());
            orderItem.setNum(num);
            orderItem.setImage(sku.getImage());
            orderItem.setPrice(sku.getPrice());
            orderItem.setName(sku.getName());
            //金额计算
            orderItem.setMoney( orderItem.getPrice()*num );
            //重量计算
            if(sku.getWeight()==null){
                sku.setWeight(0);
            }
            orderItem.setWeight(sku.getWeight()*num);
            orderItem.setCategoryId3(sku.getCategoryId());
            //优化：将数据放到redis
            Category category3 = (Category)redisTemplate.boundHashOps(CacheKey.CATEGORY).get(sku.getCategoryId());
            //根据3级分类id查2级
            if(category3==null){
                category3 = categoryService.findById(sku.getCategoryId());
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(sku.getCategoryId(), category3 );
            }
            orderItem.setCategoryId2(category3.getParentId());
            //根据2级分类id查询1级
            Category category2 = (Category)redisTemplate.boundHashOps(CacheKey.CATEGORY).get(category3.getParentId());
            if(category2==null ){
                category2 = categoryService.findById(category3.getParentId());
                redisTemplate.boundHashOps(CacheKey.CATEGORY).put(category3.getParentId(), category2 );
            }
            orderItem.setCategoryId1(category2.getParentId());

            Map map=new HashMap();
            map.put("item",orderItem);
            //默认选中
            map.put("checked",true);

            cartList.add(map);
        }
        //更新redis缓存
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
    }

    @Override
    public boolean updateChecked(String username, String skuId, boolean checked) {
        //获取购物车
        List<Map<String, Object>> cartList = findCartList(username);
        if (cartList==null){
            throw new RuntimeException("购物车为空");
        }
        boolean isOk=false;
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if (skuId.equals(orderItem.getSkuId())){
                map.put("checked",checked);
                isOk=true;
            }
        }
        //更新缓存
        if (isOk){
            redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
        }
        return isOk;
    }

    @Override
    public void deleteCheckedCart(String username) {
        List<Map<String, Object>> cartList = findCartList(username).stream()
                .filter(cart -> (Boolean) cart.get("checked") == false)
                .collect(Collectors.toList());
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);

    }

    @Autowired
    private PreferentialService preferentialService;

    @Override
    public int preferential(String username) {
        //获取需要统计金额的List<OrderItem> orderItemList
        List<OrderItem> orderItemList = findCartList(username).stream()
                .filter(cart->(Boolean) cart.get("checked")==true)
                .map(cart->(OrderItem)cart.get("item"))
                .collect(Collectors.toList());
        //按分类聚合优惠金额

        Map<Integer, IntSummaryStatistics> cartMap = orderItemList.stream()
                .collect(Collectors.groupingBy(OrderItem::getCategoryId3,
                        Collectors.summarizingInt(OrderItem::getMoney)));
        //累计优惠金额

        int allPreMoney=0;
        for (Integer categoryId : cartMap.keySet()) {
            int preMoney =preferentialService.findPreMoneyByCategoryId(categoryId,(int)cartMap.get(categoryId).getSum());
            allPreMoney+=preMoney;
        }
        return allPreMoney;
    }

    /**
     * 获取最新的购物车列表
     * @param username
     * @return
     */
    @Override
    public List<Map<String, Object>> findNewOrderItemList(String username) {
       //获取选中的购物车列表
        List<Map<String, Object>> cartList = findCartList(username);
        //循环刷新最新价格
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            Sku sku = skuService.findById(orderItem.getSkuId());
            orderItem.setPrice(sku.getPrice());
            orderItem.setMoney(orderItem.getNum()*orderItem.getPrice());
        }
        //存入缓存
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);
        return cartList;
    }
}
